package com.lktx.sso.config;

import cn.dev33.satoken.oauth2.config.SaOAuth2ServerConfig;
import cn.dev33.satoken.oauth2.strategy.SaOAuth2Strategy;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hserver.core.ioc.IocUtil;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.ioc.annotation.Configuration;
import cn.hserver.plugin.web.context.HServerContextHolder;
import cn.hutool.core.util.StrUtil;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.lktx.sso.admin.entity.SsoApp;
import com.lktx.sso.admin.entity.SsoUser;
import com.lktx.sso.admin.service.SsoAppService;
import com.lktx.sso.admin.service.SsoUserService;

import javax.security.auth.login.LoginException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Configuration
public class OAuthConfig {

   public static final Cache<String, String> CACHE_CODE_NONCE = CacheBuilder.newBuilder()
            .expireAfterWrite(5, TimeUnit.MINUTES) // 设置写入后5分钟自动过期
            .build();

    @Bean
    public SaOAuth2ServerConfig saOAuth2ServerConfig() {
        SaOAuth2ServerConfig saOAuth2ServerConfig = new SaOAuth2ServerConfig();
        saOAuth2ServerConfig.setLowerScope("openid,userinfo,oidc");
        saOAuth2ServerConfig.setIsNewRefresh(true);

        SaOAuth2Strategy.instance.notLoginView = () -> {
            String clientId = HServerContextHolder.getWebKit().httpRequest.query("client_id");
            SsoAppService bean = IocUtil.getBean(SsoAppService.class);
            SsoApp ssoApp = bean.getByClientId(clientId);
            Map<String, Object> map = new HashMap<>();
            map.put("appName", ssoApp.getAppName());
            map.put("appIcon", ssoApp.getAppIcon());
            map.put("appId", ssoApp.getSsoAppId());
            map.put("clientId", clientId);
            HServerContextHolder.getWebKit().httpResponse.sendTemplate("login.ftl", map);
            return null;
        };

        // 登录处理函数
        SaOAuth2Strategy.instance.doLoginHandle = (name, pwd) -> {
            String clientId = HServerContextHolder.getWebKit().httpRequest.query("client_id");
            SsoUserService bean = IocUtil.getBean(SsoUserService.class);
            try {
                SsoUser login = bean.login(name, pwd, clientId);
                if (login != null) {
                    StpUtil.login(login.getSsoUserId());
                    return SaResult.ok();
                }
                return SaResult.error("账号密码错误");
            } catch (LoginException e) {
                return SaResult.error("无权访问");
            }
        };

        // 授权确认视图
        SaOAuth2Strategy.instance.confirmView = (clientId, scopes) -> {
            SsoAppService bean = IocUtil.getBean(SsoAppService.class);
            SsoApp ssoApp = bean.getByClientId(clientId);
            Map<String, Object> map = new HashMap<>();
            map.put("clientId", clientId);
            map.put("scope", scopes);
            map.put("appName", ssoApp.getAppName());
            map.put("appIcon", ssoApp.getAppIcon());
            map.put("appId", ssoApp.getSsoAppId());
            HServerContextHolder.getWebKit().httpResponse.sendTemplate("confirm.ftl", map);
            return null;
        };
        return saOAuth2ServerConfig;
    }

}
